package com.fox.webapp.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.util.HashMap;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

public class ZXingEncoder {

	public static final int BLACK = 0xFF000000;
	public static final int WHITE = 0xFFFFFFFF;
	public static final int GREEN = 0xFF008000;
	public static final int RED = 0xFFFF0000;
	
	public static final void qrEncode(String contents, int onColor, int offColor, OutputStream stream){
		try{
			Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
			hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			BitMatrix bm = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, 200, 200, hint);
			MatrixToImageWriter.writeToStream(bm, "png", stream, new MatrixToImageConfig(onColor, offColor));
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws IOException {
		File f = new File("/data/test.png");
		if(f.exists() || f.createNewFile()){
			OutputStream stream = new FileOutputStream(f);
			qrEncode("http://www.econgen.com", BLACK, WHITE, stream);
			
			stream.flush();
			stream.close();
		}
	}
}
